/*
 * @Author: nengwu 409791297@qq.com
 * @Date: 2020-07-01 18:21:43
 * @LastEditors: mylesshie@gmail.com
 * @LastEditTime: 2020-09-26 21:22:19
 * @description:
 */

import React, { useState, useEffect, useRef } from 'react'
import { useDispatch } from 'react-redux'
import { useNavigation } from '@react-navigation/native'
import { View, ScrollView, Image, SafeAreaView, TouchableOpacity } from 'react-native'
import { Tab, Tabs, Button, Text, Toast } from 'native-base'
import { Input } from 'react-native-elements'
import Icon from 'react-native-vector-icons/AntDesign'
import * as WeChat from 'react-native-wechat-lib'

import styles from './styles'
import * as userActions from '@/actions/user'
const logo = require('@/assets/images/logo-large.png')
const iconWechat = require('@/assets/images/login/wechat.png')

const Login = props => {
  const navigation = useNavigation()
  const dispatch = useDispatch()

  const [loginType, setLoginType] = useState(0)
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [macCode, setMacCode] = useState('')

  const [count, setCount] = useState(0)
  const [hasBind, sethasBind] = useState(false)
  const [isGetCode, setIsGetCode] = useState(false)
  const [btnDisable, setBtnDisable] = useState(false)
  const [thirdVisible, setthirdVisible] = useState(false)
  const countRef = useRef(0)

  let timer = null
  useEffect(() => {
    WeChat.isWXAppInstalled().then(res => {
      console.log('isWXAppInstalled--:', res)
      if (res) {
        setthirdVisible(true)
      }
    })

    return () => {
      timer && clearTimeout(timer)
      timer = null
    }
  }, [])
  useEffect(() => {


  }, [])
  const _gethasBind = () => {

    dispatch(userActions.loginByPhoneSendCode(username)).then(() => {
      setIsGetCode(true)
      countRef.current = 60
      _countDown()
    })
  }

  const _onChangeText = (text, type) => {
    if (type === 'username') {
      setUsername(text)
    }
    if (type === 'password') {
      console.log('text')
      setPassword(text)
    }
    if (type === 'macCode') {
      setMacCode(text)
    }
  }

  // 倒计时
  const _countDown = () => {
    setCount(countRef.current)
    if (countRef.current <= 0) return
    timer = setTimeout(() => {
      countRef.current -= 1
      _countDown()
    }, 1000)
  }

  const _changeTab = index => {
    setLoginType(index.i)
    console.log('changeTab', index)
  }

  const _getMsgCode = () => {
    if (count) return
    if (!username) {
      return Toast.show({
        text: '请先输入手机号',
        duration: 1500
      })
    }
    dispatch(userActions.loginByPhoneSendCode(username)).then(() => {
      setIsGetCode(true)
      countRef.current = 60
      _countDown()
    })
  }

  const _goRegiste = () => {
    navigation.navigate('Registe')
  }
  const _goDetail = async () => {
    let loginData = {}
    try {
      loginData = await global.storage.load({ key: 'loginState' })
      // return
    } catch (err) {
      // loginData = {}
    }

    // console.log('22222222')

    // console.log(JSON.stringify(loginData.uid))
    // console.log(JSON.stringify(loginData.token))
    // // console.log(testId)
    // console.log('2222222')
    return loginData



  }

  const _submit = () => {
    if (btnDisable) return
    // 验证码登录
    if (loginType === 0) {
      if (!username || !macCode) {
        return Toast.show({
          text: '请输入手机号和验证码',
          duration: 1500
        })
      }
      if (!isGetCode) {
        return Toast.show({
          text: '请先获取验证码',
          duration: 1500
        })
      }
      setBtnDisable(true)
      dispatch(userActions.loginByPhone(username, macCode)).then(res => {
        global.storage
          .save({
            key: 'loginState',
            data: {
              token: res.userToken,
              uid: res.userId
            }
          })
          .then(() => {
            navigation.goBack()
          })
        setBtnDisable(false)
      }).catch(() => {
        setBtnDisable(false)
      })
    }

    // 密码登录
    if (loginType === 1) {
      if (!username || !password) {
        return Toast.show({
          text: '请输入手机号和密码',
          duration: 1500
        })
      }
      setBtnDisable(true)
      dispatch(userActions.loginByPsd(username, password)).then(res => {
        global.storage
          .save({
            key: 'loginState',
            data: {
              token: res.userToken,
              uid: res.userId
            }
          })
          .then(() => {
            navigation.navigate('BindPhone')
            // navigation.goBack()
          })
        setBtnDisable(false)
      }).catch(() => {
        setBtnDisable(false)
      })
    }
  }

  const _cancelLogin = () => {
    navigation.goBack()
  }

  const _wxLogin = () => {
    console.log('微信 login')
    WeChat.sendAuthRequest('snsapi_userinfo').then(wechatRes => {
      console.log('--------------snsapi_userinfo---------------', wechatRes)
      console.log(wechatRes.code)
      return dispatch(userActions.wechatLogin(wechatRes.code))
    }).then(res => {
      global.storage
        .save({
          key: 'loginState',
          data: {
            token: res.userToken,
            uid: res.userId,
            bind: res.bind
          }
        })
      if (res.bind) {
        sethasBind(true)
      } else {
        sethasBind(false)
      }
      console.log("------------------------")
      console.log(res)
      console.log("------------------------")

        .then(() => {
          if (hasBind) {
            navigation.goBack()
          } else {
            navigation.navigate('BindPhone')
          }


        })
    }).catch(err => {
      console.log('--------------snsapi_userinfo---------------:', err)
    })
  }

  return (
    <>
      <SafeAreaView style={styles.wrap}>
        <ScrollView
          style={styles.container}
          contentInsetAdjustmentBehavior="automatic"
        >
          <Button iconLeft transparent style={styles.closeBtn} onPress={_cancelLogin}>
            <Icon
              name="close"
              color="#333"
              size={25}
            />
          </Button>
          <View style={styles.top}>
            <Image source={logo} style={styles.logo} />
          </View>
          <View style={styles.formWrap}>
            <Tabs
              tabBarUnderlineStyle={styles.tabUnderline}
              tabContainerStyle={styles.tabContainer}
              onChangeTab={_changeTab}
            >
              <Tab
                heading="验证码登录"
                tabStyle={styles.tabStyle}
                activeTabStyle={styles.tabStyle}
                textStyle={styles.tabTextStyle}
                activeTextStyle={styles.activeTextStyle}
              >
                <View style={styles.inputWrap}>
                  <Input
                    placeholder="请输入手机号"
                    value={username}
                    maxLength={11}
                    onChangeText={text => _onChangeText(text, 'username')}
                  />
                  <Input
                    placeholder="请输入验证码"
                    value={macCode}
                    onChangeText={text => _onChangeText(text, 'macCode')}
                    maxLength={6}
                    rightIcon={
                      count > 0 ? (
                        <Button transparent style={styles.smsBtn} disabled>
                          <Text style={styles.smsBtnDisable}>
                            {count}s后重新获取
                          </Text>
                        </Button>
                      ) : (
                        <Button
                          transparent
                          style={styles.smsBtn}
                          onPress={_getMsgCode}
                        >
                          <Text style={styles.smsBtnText}>获取验证码</Text>
                        </Button>
                      )
                    }
                  />
                </View>
              </Tab>
              <Tab
                heading="密码登录"
                tabStyle={styles.tabStyle}
                activeTabStyle={styles.tabStyle}
                textStyle={styles.tabTextStyle}
                activeTextStyle={styles.activeTextStyle}
              >
                <View style={styles.inputWrap}>
                  <Input
                    placeholder="请输入手机号"
                    value={username}
                    onChangeText={text => _onChangeText(text, 'username')}
                  />
                  <Input
                    placeholder="请输入密码"
                    secureTextEntry={true}
                    maxLength={16}
                    value={password}
                    onChangeText={text => _onChangeText(text, 'password')}
                  />
                </View>
              </Tab>
            </Tabs>
          </View>
          <Button rounded block style={styles.loginBtn} onPress={_submit}>
            <Text style={styles.btnText}>登录</Text>
          </Button>
          <Button transparent style={styles.registBtn} onPress={_goRegiste}>
            <Text style={styles.registText}>没有账号？去注册</Text>
          </Button>
          {thirdVisible ?
            <View>
              <View style={styles.thirdLoginBox}><Text style={styles.thirdBoxTitle}>第三方登录</Text></View>
              <View style={styles.loginTypes}>
                <View style={styles.loginItem}>
                  <TouchableOpacity onPress={_wxLogin} style={styles.loginItem}>
                    <View style={styles.loginItemIconBox}>
                      <Image source={iconWechat} style={styles.loginItemIcon} />
                    </View>
                    <View><Text style={styles.loginName}>微信</Text></View>
                  </TouchableOpacity>
                </View>
              </View>
            </View> : null}
        </ScrollView>
      </SafeAreaView>
    </>
  )
}

export default Login
